#!/usr/bin/env tclsh
# $Id: sql.tcl 9ce65bed8ef4 2012/08/26 02:14:51 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# __version__  = "$Revision: 9ce65bed8ef4 $"
# __author__   = "$Author: pgurumur $"
# __modified__ = "$Date: 2012-08-26 02:14:51Z $"

# lappend ::auto_path sqlite3.6.22 
# lappend ::auto_path mysqltcl-3.05
lappend ::auto_path venya
package require sqlite3
package require mysqltcl 3.0
package require stdlib

source config.tcl

namespace eval sql {
   namespace export sql
   namespace export basename
   set version 1.0
   set progname ""
   set dbh ""
   set type ""
}

proc sql::basename { program } {
   global progname
   if {[string length $program] > 0} {
      set progname $program
   }
}

proc sql::sqlite database {
   global dbh
   set retval ""
   if {[string length $database]}
      sqlite3 db $database
      set retval $db
      set dbh $db
      set type "sqlite"
   }

   return $retval
}

proc sql::mysql { database host user pass } {
   global sqlerr
   global dbh
   set retval ""
   set flag [string length $database] 
   set flag [expr $flag && [string length $host]]
   set flag [expr $flag && [string length $user]]
   set flag [expr $flag && [string length $pass]]
   if {$flag == 1} {
      if {[catch {set retval mysql::connect -host "localhost" -user "djanet" -password "1oS9XckUcTAHc5rjlcPt1" -db "netdot"} err]} {
         set sqlerr $err
         set retval ""
      } else {
         set dbh $retval
         set type "mysql"
      }
   } else {
      set sqlerr "one or more required arguments is missing!"
   }

   return $retval
}

proc sql::close {} {
   global dbh
   global type

   if {$type == "sqlite"} {
      $dbh close
   } elseif {$type == "mysql"} {
      mysql::close $dbh
   }
}

proc sql::error {} {
   set retval ""
   global sqlerr
   if {$type == "sqlite"} {
      set retval $sqlerr
   } elseif {$type == "mysql"} {
      set retval mysql::mysqlstatus(message)
   }
}


proc sql::? {} { lsort [info procs ::sql::*] }
package provide sql $sql::version

